package com.vogue.supplymall.upload.controller;

import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.UploadInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.exception.UploadException;
import com.vogue.supplymall.upload.domain.service.UploadService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 上传头像的处理
 *
 * @author 崔岳
 */
@RestController
public class HeadimgUploadController extends BaseController {

    /**
     * The constant log.
     */
    public static final Logger LOGGER_HEADIMGUPLOADCONTROLLER = LoggerFactory.getLogger(HeadimgUploadController.class);

    /**
     * The constant MODULE_NAME.
     */
    public static final String MODULE_NAME = "user";
    @Resource
    private UploadService uploadService;

    /**
     * Upload refund img response entity. 上传图片
     *
     * @param appver     the appver
     * @param uploadInfo the upload info
     * @return the response entity
     */
    @RequestMapping(value = "/is/{appver}/upload/user/headimg", method = RequestMethod.POST)
    public ResponseEntity<Object> uploadHeadimg(@PathVariable("appver") String appver,
                                                @RequestBody UploadInfo uploadInfo) {
        LOGGER_HEADIMGUPLOADCONTROLLER.info("upload user head image start >>>>>> ");
        if (null == uploadInfo.getPicData()
                || null == uploadInfo.getExtension()) {
            throw new UploadException("");
        }
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        uploadInfo.setDataid(user.getLoginId());
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        resultInfo.setResult(true);
        uploadInfo.setModuleName(MODULE_NAME);
        resultInfo.setData(uploadService.uploadResource(uploadInfo));
        LOGGER_HEADIMGUPLOADCONTROLLER.info(" <<<<<< upload user head image end");
        user.setHeadImgUrl((String) resultInfo.getData());
        try {
            SecurityUtils.getSubject().getSession().touch();
        } catch (Exception ex) {

        }
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
    }

}
